package com.zk.iotgateway.net.common;

import com.zk.iotgateway.bizhandler.IHandler;
import com.zk.iotgateway.classes.loader.FileSystemClassLoader;
import com.zk.iotgateway.domain.param.IotConfigDO;
import com.zk.iotgateway.service.IotConfigService;
import com.zk.iotgateway.util.NettyUtil;
import com.zk.iotgateway.util.SpringUtil;
import com.zk.iotgateway.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.util.ReferenceCountUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 网关公共
 * 编解码一体
 * 应该具有容错性
 * @author:mn.m
 * @create 2019-07-03 上午 09:26
 **/
@Component
@Scope("prototype")
public class IotCommonCodec extends ByteToMessageCodec {

      @Autowired
      private IotConfigService iotConfigService;
      private IHandler iHandler;
    /**
     * @Author mn
     * @Description  编码器
     * @Date 上午 09:28 2019/7/3 0003
     * @Param
     * @return
     **/
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        IotConfigDO configByPort = iotConfigService.findConfigByPort(NettyUtil.returnPort(ctx));
        if (configByPort!= null){
            String beanName = StringUtils.getBeanName(configByPort.getHandler());
            iHandler = (IHandler) SpringUtil.getBean(beanName);
            iHandler.encode(ctx,msg,out);
        }else {
            if (msg instanceof String){
                String o=(String) msg;
                byte[] dist= StringUtils.decodeHex(o);
                out.writeBytes(dist);
                ReferenceCountUtil.release(o);
            }else if (msg instanceof Byte){
                out.writeBytes((byte[]) msg);
                ReferenceCountUtil.release(msg);
            }

        }
    }

    /**
     * @Author mn
     * @Description 解码器
     * @Date 上午 09:28 2019/7/3 0003
     * @Param
     * @return
     **/
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {
        System.out.println("网关--"+ctx.channel().localAddress());
        IotConfigDO configByPort = iotConfigService.findConfigByPort(NettyUtil.returnPort(ctx));
        if (configByPort!= null){
            String beanName = StringUtils.getBeanName(configByPort.getHandler());
            iHandler = (IHandler) SpringUtil.getBean(beanName);
            iHandler.decode(ctx,in,out);
        }
    }
}
